var bLog = requireMod("b-log");
var common = requireMod("common");
var dsAppId = getSysConfig("dsAppId");

function log(data){
    var dat = {};
    Object.keys(data).forEach(function(key){
        if (key !== "type") {
            var type_dat = data[key];
            if (common.isObject(type_dat) || common.isArray(type_dat)) {
                Object.keys(type_dat).forEach(function(type_key){
                    dat[key+"_"+type_key] = type_dat[type_key];
                });
            } else {
                dat[key] = type_dat;
            }
        }
    });

    bLog.log(data.app || "ppp", data.log_type, dat);
    dat = null;

    // bLog.flushBlock();
    // bLog.dumpFile();
}

var noCacheHeader = "no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0";

function onCollect(ctx) {
    var data;
    if (ctx.query.cd) {
        try {
            data = JSON.parse(ctx.query.cd);
        } catch(e) {
            console.error(e);
        }
    }
    data.date = common.date("Y-m-d h:i:s",new Date());
    log(data);
    ctx.status = 200;
    ctx.set("content-type","image/gif");
    ctx.set("cache-control",noCacheHeader);
    ctx.body = "";
    ctx.res.end();
}

function onTrack(ctx) {
    log(
        ctx.state.collect
    );

    ctx.status = 200;
    ctx.set("content-type","image/gif");
    ctx.set("cache-control",noCacheHeader);
    ctx.body = "";
}

module.exports = {
    "/collect":["GET",onCollect]
    ,"/collect/pageview":["GET",onTrack]
    ,"/collect/click":["GET",onTrack]
}
